package com.glsc.ngateway.platform.controller.it;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.PageConstant;
import com.glsc.ngateway.common.api.platform.dto.it.CloudManageExport;
import com.glsc.ngateway.common.api.platform.dto.it.ParamSearchCloudDto;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItCloudDevice;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItCloudList;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.service.it.CloudService;
import com.glsc.ngateway.platform.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.glsc.ngateway.common.api.common.enums.Constant.CLOUD_ADMIN;


@RestController
@RequestMapping("/it/cloud")
@Api(value = "云管理", tags = {"云管理"})
public class CloudManageController {

    private static final Logger logger = LoggerFactory.getLogger(CloudManageController.class);

    public static final int MEMBER_READ_ONLY = 0;
    public static final int MEMBER_PROJECT_LEADER = 1;

    @Autowired
    private CloudService cloudService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserCache userCache;
    @Autowired
    private UserService userService;
    @Value("${export.it}")
    public String itpath;

    // 查询云平台清单
//    @RequestMapping(method = RequestMethod.GET, value = "query")
//    @ApiOperation(value = "查询云平台清单", notes = "查询云平台清单")
//    public PlatformResponseNew queryCloudList(
//            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
//            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {
//        if (pageNo == null) {
//            pageNo = 1;
//        }
//        if (pageSize == null) {
//            pageSize = PageConstant.PageSize;
//        }
//        PlatformUserDto user = userCache.get(request);
//        String userid = user.getUserid();
//        if ("admin".equals(user.getUsername())) {
//            userid = null;
//        }
//        Page<ItCloudDevice> result = cloudService.queryCloudList(pageNo, pageSize, userid);
//        PlatformResponseNew ret = PlatformResponseNew.success();
//        ret.setData(result);
//        return ret;
//    }

    /*
     * 提交或修改项目
     */
    @RequestMapping(method = RequestMethod.POST, value = "addOrUpdate")
    @ApiOperation(value = "提交或修改项目", notes = "提交或修改项目")
    public PlatformResponse<Void> addOrUpdateCloud(@RequestBody ItCloudDevice itCloudDevice) {
        PlatformUserDto user = userCache.get(request);
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if (itCloudDevice.getDevId() == null ){
            //新增情况
            if (!"itadmin".equals(user.getUsername()) && !roleNames.contains("itadmin") && !roleNames.contains(CLOUD_ADMIN)) {
                return PlatformResponse.failedMsg("addOrUpdate接口，没有该功能权限。");
            }
        } else {
            //修改情况
            if (!"itadmin".equals(user.getUsername()) && !roleNames.contains("itadmin") && !roleNames.contains(CLOUD_ADMIN)){
                //查找记录
                ItCloudDevice dev = cloudService.findByDevId(itCloudDevice.getDevId());
                if (!dev.getUserId().equals(itCloudDevice.getUserId())){
                    return PlatformResponse.failedMsg("addOrUpdate接口，没有该功能权限。");
                }
            }
        }
        cloudService.addOrUpdateCloud(itCloudDevice);
        return PlatformResponse.successMsg("创建或修改成功");
    }

    @RequestMapping(method = RequestMethod.POST, value = "delete")
    @ApiOperation(value = "删除", notes = "删除")
    public PlatformResponse<Void> deleteCloudDevice(@RequestBody String devId) {
        if (StringUtils.isEmpty(devId)) {
            return PlatformResponse.failedMsg("deleteCloudDevice接口，id为空。");
        }
        PlatformUserDto user = userCache.get(request);
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if (!"itadmin".equals(user.getUsername()) && !roleNames.contains("itadmin") && !roleNames.contains(CLOUD_ADMIN)) {
            return PlatformResponse.failedMsg("deleteCloudDevice接口，没有该功能权限。");
        }
        JSONObject jsonObject = (JSONObject) JSON.parse(devId);
        String id = jsonObject.getString("devId");
        if (StringUtils.isNotEmpty(id)) {
            cloudService.deleteCloud(id);
        }
        return PlatformResponse.successMsg("删除云成功");
    }
    // 查询云平台区域
    @RequestMapping(method = RequestMethod.GET, value = "/cloudArea/listAll")
    @ApiOperation(value = "查询云平台区域", notes = "查询云平台区域")
    public PlatformResponse<List<ItCloudList>> queryCloudAreaList() {
        List<ItCloudList> result = cloudService.queryCloudAreaList();
        return PlatformResponse.successData(result);
    }


    //导出excel
    @RequestMapping(method = RequestMethod.POST, value = "export")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public ResponseEntity<byte[]> exportCloudOutPut() throws IOException {
        /*验证新增权限begin*/
//        String userId = CookieUtil.getParaFromCookie(request, "userId");
//        List<String> userRoles = userService.getUserAllRolesById(userId);
//        boolean isAuth = false; //是否有权限新增
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        if (!isAuth)
//            return new JsonResult(ErrorCode.E9999.getCode(), "抱歉，您未获得导出权限，请联系管理员");
        /*验证新增权限end*/
        List<CloudManageExport> result = cloudService.exportCloudOutPut();
        List<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();

        WriteSheet sheet = EasyExcel.writerSheet(0, "云设备").build();
        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(result);
        multipleSheelPropety.setSheet(sheet);

        list.add(multipleSheelPropety);

        String fileName = itpath + "cloud.xlsx";
        ExcelUtil.writeWithMultipleSheel(fileName, list);

        String targetName = fileName;
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }
//
//    //导出excel
//    @RequestMapping(value = "/queryCloudOutPut", method = {RequestMethod.GET, RequestMethod.POST})
//    public Object queryCloudOutPut(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        /*验证新增权限begin*/
//        String userId = CookieUtil.getParaFromCookie(request, "userId");
//        List<String> userRoles = userService.getUserAllRolesById(userId);
//        boolean isAuth = false; //是否有权限新增
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        if (!isAuth)
//            return new JsonResult(ErrorCode.E9999.getCode(), "抱歉，您未获得导出权限，请联系管理员");
//        /*验证新增权限end*/
//        String scd = (String) request.getParameter("scd");
//        List<CloudDeviceExport> result = cloudServerService.queryCloudOutPut(scd);
//        ArrayList<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();
//
//        WriteSheet sheet = EasyExcel.writerSheet(0, "云主机").build();
//        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
//        multipleSheelPropety.setData(result);
//        multipleSheelPropety.setSheet(sheet);
//
//        list.add(multipleSheelPropety);
//
//        String fileName = "d:/ypt.xlsx";
//        ExcelUtil.writeWithMultipleSheel(fileName, list);
//
//        response.setContentType("application/octet-stream");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//
//        OutputStream output = response.getOutputStream();
//        byte[] bytes = FileUtil.readByteFromFilePath(fileName);
//        if (null == bytes) {
//            output.close();
//            return null;
//        }
//        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
//        int len;
//        byte[] buf = new byte[1024];
//        while ((len = in.read(buf)) != -1) {
//            output.write(buf, 0, len);
//        }
//        output.flush();
//        output.close();
//        return null;
//    }
//
//
//    //搜索云平台
//    @RequestMapping(value = "/searchCloud", method = {RequestMethod.GET, RequestMethod.POST})
//    public Object searchCloud(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String userId = CookieUtil.getParaFromCookie(request, "userId");
//        String scd = (String) request.getParameter("scd");
//        List<Map<String, Object>> result = cloudServerService.searchCloud(scd, userId);
//
//        // 整理输出信息
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.saveResultSet(result);
//        return jsonResult;
//    }
//
//    //搜索云平台名称
//    @RequestMapping(value = "/multiSearch", method = {RequestMethod.GET, RequestMethod.POST})
//    public Object multiSearchCloudDevice(com.jlwang.rest.cloud.boundary.CloudServerAddOrUpdateInput input,
//                                         HttpServletRequest request, HttpServletResponse response) throws Exception {
//        /*验证新增权限begin*/
//        String userId = CookieUtil.getParaFromCookie(request, "userId");
//        List<String> userRoles = userService.getUserAllRolesById(userId);
//        boolean isAuth = false; //是否有权限新增
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        if (!isAuth)
//            return new JsonResult(ErrorCode.E9999.getCode(), "抱歉，您未获得该权限，请联系管理员");
//        /*验证新增权限end*/
//        Map<String, Object> cloudServerInfo = BeanUtil.bean2Map(input);
//
//        List<Map<String, Object>> result = cloudServerService.multiSearch(cloudServerInfo);
//
//        JsonResult jsonResult = new JsonResult();
//        jsonResult.saveResultSet(result);        //保存搜索数据
//        return jsonResult;
//    }


    //搜索云平台
    @RequestMapping(method = RequestMethod.POST, value = "search")
    @ApiOperation(value = "搜索云平台", notes = "搜索云平台")
    public PlatformResponse<Page<ItCloudDevice>> searchCloud(@RequestBody ParamSearchCloudDto params) {
        if (params.getPageNo() == null) {
            params.setPageNo(PageConstant.PageNo);
        }
        if (params.getPageSize() == null) {
            params.setPageSize(PageConstant.PageSize);
        }
        PlatformUserDto user = userCache.get(request);
        String userId = user.getUserid();
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if ("itadmin".equals(user.getUsername()) || roleNames.contains("itadmin") || roleNames.contains(CLOUD_ADMIN)) {
            userId = null;
        }

        String cloudId = params.getCloudId();
        String application = params.getApplication();
        String cloudStyle = params.getCloudStyle();
        Integer cloudArea = params.getCloudArea();
        String userAccount = params.getUserAccount();
        if (StringUtils.isNotEmpty(userAccount)) {
            PlatformUserDto u = userService.findByUsername(userAccount);
            if (u != null) {
                userId = u.getUserid();
            }
        }

        if (StringUtils.isEmpty(params.getApplication())) {
            application = null;
        }
        if (StrUtil.isEmpty(params.getCloudId())) {
            cloudId = null;
        }
        if (StrUtil.isEmpty(params.getCloudStyle())) {
            cloudStyle = null;
        }
        if (params.getCloudArea() == null || params.getCloudArea() == 0) {
            cloudArea = null;
        }

        Page<ItCloudDevice> result = cloudService.searchCloud(params.getPageNo(), params.getPageSize(), cloudId, cloudStyle, cloudArea, userId, application);
        return PlatformResponse.successData(result);
    }


}